/* s2 - find first zero byte by testing each one-for-one in a loop
   Copyright (C) 2018 Ariadne Devos

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <sHT/bitops.h>
#include <sHT/nospec.h>
#include <stdint.h>
#include <endian.h>

_Static_assert(sizeof(uint64_t) == 8, "code assumes 8-bit bytes");
_Static_assert(sHT_word_zero_index_prepare(UINT64_C(23)) == UINT64_C(23), "inconsitent with <sHT/bitops.h>");

/* noinline is for benchmarking */
__attribute__((noinline))
int
sHT_word_zero_index64(uint64_t word)
{
	size_t i = 0;
	uint64_t mask = 0xff00000000000000;
	while (sHT_test_hidden2(word, mask, word & mask)) {
		i++;
		mask >>= 8;
	}
	i &= 7;
	_Static_assert((BYTE_ORDER == LITTLE_ENDIAN) || (BYTE_ORDER == BIG_ENDIAN), "unsupported endianness");
	if (BYTE_ORDER == LITTLE_ENDIAN)
		i = 8 - i;
	return i;
}
